<template>
	<view class="equip-change-page">
		<view class="form-wrap">
			<u--form :model="form" ref="uform" labelPosition="left" :labelWidth="104">
				<u-form-item label="井点编号" borderBottom customStyle="height:80rpx;">
					<u--input v-model="form.pointNo" disabled disabledColor="#fff" border="none"></u--input>
				</u-form-item>
				<u-form-item label="原设备编号" borderBottom customStyle="height:80rpx;">
					<u--input v-model="form.lastEquNo" disabled disabledColor="#fff" border="none"></u--input>
				</u-form-item>
				<u-form-item label="设备类型" borderBottom @click="
            equTypeShow = true;
            hideKeyboard();
          " customStyle="height:80rpx;">
					<u--input :value="equTypeValue" disabled disabledColor="#fff" border="none" placeholder="请选择设备类型"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="新设备编号" required borderBottom customStyle="height:80rpx;">
					<u--input v-model="form.equNo" border="none" placeholder="请扫码或输入"></u--input>
					<u-icon slot="right" name="scan" color="#3576F2" size="80rpx" @click="handleScan('equNo')"></u-icon>
				</u-form-item>
				<u-form-item label="新SIM卡号" borderBottom customStyle="height:80rpx;">
					<u--input v-model="form.sim" border="none" placeholder="请扫码或输入"></u--input>
					<u-icon slot="right" name="scan" color="#3576F2" size="80rpx" @click="handleScan('sim')"></u-icon>
				</u-form-item>
				<u-form-item label="补偿值" :required="[1,7].includes(+form.equType)" borderBottom customStyle="height:80rpx;">
					<u--input v-model="form.compensate" type="number" border="none" placeholder="请输入补偿值"></u--input>
				</u-form-item>
				<u-form-item label="设备厂家" required borderBottom disabledColor="#fff" customStyle="height:80rpx;">
					<u-radio-group v-model="form.brand" placement="row">
						<u-radio :name="1" label="自研" :size="16" :labelSize="16" :customStyle="{marginRight: '8px'}"></u-radio>
						<u-radio :name="2" label="采购" :size="16" :labelSize="16"></u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="安装图片" borderBottom disabledColor="#fff" customStyle="height:190rpx;">
					<u-upload width="200rpx" height="200rpx" :previewFullImage="true" :fileList="tp" name="tp" @afterRead="afterRead"
						@delete="deletePic" :multiple="false" :maxCount="1">
					</u-upload>
				</u-form-item>
			</u--form>
		</view>
		<view class="page-btn-wrap">
			<view class="btn-item">
				<u-button type="primary" text="提交" customStyle="margin: auto 0" @click="submit"></u-button>
			</view>
		</view>
		<u-picker :show="equTypeShow" keyName="name" title="设备类型" :columns="[equTypeList]" @cancel="equTypeShow = false"
			@confirm="equTypeSelect"></u-picker>
	</view>
</template>
<script>
	import {
		equipPartInfoEdit,
		addEquipOperateLog
	} from '@/api/equip.js';
	import {
		getDictItemInfo
	} from '@/api/system';
	import {
		commonUploadPic
	} from '@/api/houseInfo.js'
	
	export default {
		data() {
			return {
				setEquip: null,
				tp: [],
				form: {
					id: '', // 设备id
					sim: '', // 新SIM卡号
					equNo: '', // 新设备编号 必填项
					equType: '', // 设备类型 必填项 字典值
					compensate: '', // 补偿值
					pointNo: '', // 井点编号 带入
					lastEquNo: '', // 原设备编号
					picData: '',
				},
				eventChannel: null,
				equTypeShow: false,
				equTypeValue: '',
				equTypeList: [], // 设备类型列表-字典值列表
			};
		},
		onLoad(option) {
			const eventChannel = this.getOpenerEventChannel();
			this.eventChannel = eventChannel;
			eventChannel.on('sendEquipInfo', (data) => {
				this.setEquip = data;
				console.log('setEquip', data);
				this.init(data);
			});
		},
		onUnload() {
			this.eventChannel.off('sendEquipInfo');
		},
		methods: {
			init(data) {
				this.form.id = data.id;
				this.form.equType = data.equType;
				this.form.pointNo = data.pipPointNo; // 井点编号 带入
				this.form.lastEquNo = data.equNo; // 原设备编号
				this.form.brand = data.brand; // 原设备编号
				//字典 设备类型 	ps_equ_type
				this.getDictListFun('ps_equ_type');
			},
			async submit() {
				try {
					const {
						equNo,
						equType,
						compensate,
						brand
					} = this.form;
					if([1,7].includes(+equType)&& !compensate){
						uni.showToast({
							icon: 'error',
							title: '请输入补偿值',
						});
						return;
					}
					if (!(equNo && equType &&brand)) {
						uni.showToast({
							icon: 'error',
							title: '请先完成表单项（设备编号、设备类型、设备厂家）',
						});
						return;
					}
					const params = {
						...this.form,						
						picData: JSON.stringify(this.tp.map(item => item.url).map(url =>
							({
								name: url.substring(url.lastIndexOf('/') + 1),
								path: url
							}))),
							onlintStatus:1
					};
					const res = await equipPartInfoEdit(params);
					if (!res.data.success) {
						uni.showToast({
							title: res.data.message,
							duration: 3000,
							icon: 'Error',
						});
						return;
					} else {
						const {
							pointNo,
							equNo,
							equType
						} = this.form;
						const {
							onlintStatus
						} = this.setEquip;
						const operationParams = {
							pointNo,
							equNo,
							equType,
							status: onlintStatus,
							operateType: 3,
							operateSource: 2,
							operateTime: new Date().format('yyyy-MM-dd hh:mm:ss'),
						};
						await addEquipOperateLog(operationParams);
						uni.showToast({
							title: '已提交',
						});
						this.eventChannel.emit('refresh');
						uni.navigateBack();
					}
				} catch (e) {
					//TODO handle the exception
				}
			},
			async getDictListFun(dictCode) {
				try {
					const res = await getDictItemInfo({
						dictCode,
					});
					const equType = this.form.equType;
					this.equTypeList = (res.data.result || []).map((x) => {
						if (equType === x.itemValue) {
							this.equTypeValue = x.itemText || '';
						}
						return {
							name: x.itemText,
							label: x.itemText,
							value: x.itemValue,
						};
					});
				} catch (e) {
					//TODO handle the exception
				}
			},
			belongSelect(res) {
				const selectItem = res.value[0];
				this.form.equBelong = selectItem.type;
				this.equBelongValue = selectItem.name;
				this.belongShow = false;
			},
			equTypeSelect(res) {
				const selectItem = res.value[0];
				this.form.equType = selectItem.value;
				this.equTypeValue = selectItem.name;
				this.equTypeShow = false;
			},
			handleScan(key) {
				// 允许从相机和相册扫码
				uni.scanCode({
					scanType: ['qrCode'],
					success: (res) => {
						if (res.result) {
							// equNo sim
							this.form[key] = res.result;
						}
					},
					fail: (res) => {
						uni.showToast({
							icon: 'error',
							title: '未识别到二维码',
						});
					},
				});
			},
			hideKeyboard() {
				uni.hideKeyboard();
			},			
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[event.name].length
				lists.map((item) => {
					this[event.name].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[event.name][fileListLen]
					this[event.name].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			async uploadFilePromise(url) {
				const res = await commonUploadPic(url)
				console.log(res, 'uploadHttp')
				let d = JSON.parse(res.data)
				if (d.code == 200) {
					return d.result.picUrl
				}
			},
			// 删除图片
			deletePic(event) {
				this.tp.splice(event.index, 1)
			},
		},
	};
</script>
<style lang="scss" scoped>
	.equip-change-page {
		min-height: 100vh;
		background-color: #fff;
	}

	.form-wrap {
		padding: 0 32rpx;
		margin-bottom: 180rpx;
	}

	.page-btn-wrap {
		position: fixed;
		display: flex;
		bottom: 0;
		width: 100%;
		height: 166rpx;
		box-shadow: 0 -4rpx 24rpx 0 #00000014;
		background: white;
		z-index: 99;
	}

	.btn-item {
		padding: 16rpx 32rpx 0 32rpx;
		width: 100%;
		height: 100%;
	}
</style>